package com.example.zhaohang.employmentapp;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.zhaohang.been.RegistStataBeen;
import com.example.zhaohang.been.UpDataBeen;
import com.example.zhaohang.contect.UriContect;
import com.example.zhaohang.utils.GsonUtil;
import com.example.zhaohang.utils.ToastMake;
import com.example.zhaohang.utils.Utils;
import com.example.zhaohang.weigit.NoScrollViewPager;
import com.example.zhaohang.weigit.SimpleCardFragment;
import com.flyco.tablayout.SlidingTabLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class MainActivity extends BasicActivity implements View.OnClickListener {
    private static final int      READSDK = 15;
    private final        String[] title   = {"主驾", "副驾", "后排左", "后排右"};
    private SlidingTabLayout  mTabLayout;
    private NoScrollViewPager mViewPager;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private MyPagerAdapter mAdapter;
    private long exitTime = 0;


    private int     vs_name1      = 0;
    private int     vs_name2      = 0;
    private int     vs_name3      = 0;
    private int     sv_name1      = 0;
    private int     sv_name2      = 0;
    private int     sv_name3      = 0;
    private boolean hasPermission = false;
    private int     myProgress    = 0;
    private TextView        mShare;
    private DrawerLayout    mDrawer;
    private LinearLayout    mMoney;
    private LinearLayout    mCustomer;
    private LinearLayout    mSetting;
    private LinearLayout    mFix;
    private RegistStataBeen mBeen;
    private int             mSize;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_main);

        mTabLayout = findViewById(R.id.slidingtablayout);
        mViewPager = findViewById(R.id.viewpager);
        mShare = findViewById(R.id.share);
        mDrawer = findViewById(R.id.drawer);

        //侧滑菜单
        mMoney = findViewById(R.id.money);
        mCustomer = findViewById(R.id.customer);
        mSetting = findViewById(R.id.setting);
        mFix = findViewById(R.id.fix);

        mMoney.setOnClickListener(this);
        mCustomer.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        mFix.setOnClickListener(this);

        setLeftShow(1, R.mipmap.user);
        setRightShow(1, R.mipmap.message);
        //点击小人去登录界面
        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:打开侧滑菜单
                mDrawer.openDrawer(GravityCompat.START);
            }
        });
        //点击邮件
        getRight_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, EmailActivity.class));
            }
        });


        hasPermission();
        //无网状态
        if (isConnected(MainActivity.this)) {
            UpdataApk();
        }

        mShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        chice();
    }

    private void chice() {
        String phone = Utils.getString();
        if (TextUtils.isEmpty(phone) || !Utils.isMobileMian(phone)) {
            mFragments.clear();
            for (int i = 0; i < title.length; i++) {
                if (i == 0) {
                    mFragments.add(SimpleCardFragment.getInstance(i + "", title[i], title[i]));
                } else {
                    mFragments.add(SimpleCardFragment.getInstance(i + 1 + "", title[i], title[i]));
                }
            }
            //一句代码就可以控制是否滑动
            mViewPager.setNoScroll(true);
            mAdapter = new MyPagerAdapter(getSupportFragmentManager());
            mViewPager.setAdapter(mAdapter);
            mTabLayout.setViewPager(mViewPager, title);
            skipOtherActivity(LoginActivity.class, true);
            return;
        } else {
            Map<String, String> map = new HashMap<>();
            map.put("phone", phone);
            String json = GsonUtil.parseMapToJson(map);
            showProgrees("加载中请稍等....");
            OkHttpUtils
                    .postString()
                    .url(UriContect.STATUS)
                    .content(json)
                    .mediaType(MediaType.parse("application/json; charset=utf-8"))
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            hideProgree();

                            //原则上进入登录界面

                            //                            Utils.runOnUIThread(new Runnable() {
                            //                                @Override
                            //                                public void run() {
                            //
                            //                                    skipOtherActivity(LoginActivity.class,true);
                            //                                }
                            //                            });
                            return;
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            hideProgree();
                            mBeen = GsonUtil.parseJsonToBean(response, RegistStataBeen.class);

                            if (mBeen == null) {
                                skipOtherActivity(LoginActivity.class, true);
                                return;
                            }
                            if (!TextUtils.equals(mBeen.getStatus(), "1")) {
                                ToastMake.showToast(mBeen.getMsg());
                                //                                skipOtherActivity(LoginActivity.class,true);
                                return;
                            } else {
                                //首先记录整个appkey

                                MyApplayCation.phone = mBeen.getPhone();

                                //TODO:这里的position应该是个集合,并且还要增加一个字段,
                                String type = mBeen.getType();
                                //如果状态是1表示尚未完成车辆信息
                                if (TextUtils.equals("1", type)) {
                                    //如果注册了没有了注册汽车
                                    startActivity(new Intent(MainActivity.this, BasicInfoActivity.class));
                                } else if (TextUtils.equals("2", type)) {
                                    //如果车辆状态是2，表示尚未扫码
                                    //TODO:如果没有扫描完。进入扫描界面
                                    startActivity(new Intent(MainActivity.this, ChioceSetActivity.class));
                                } else if (TextUtils.equals("3", type)) {
                                    //表示全部完成
                                } else {
                                    //如果有其他的，表示再加入扫码座椅
                                    startActivity(new Intent(MainActivity.this, ChoceOtherActivity.class));
                                }

                                //显示消息个数
                                String state = mBeen.getState();
                                if (TextUtils.equals(state, "1")) {
                                    setRightShow(1, R.mipmap.message);
                                } else {
                                    setRightShow(1, R.mipmap.message_red);
                                }
                                //显示加载照片
                                //设置viewPager关联,并且解决索引越界的问题
                                if (mBeen.getData() != null) {
                                    mSize = mBeen.getData().size();
                                } else {
                                    mSize = 0;
                                }
                                mFragments.clear();
                                for (int i = 0; i < title.length; i++) {
                                    //创建的单例,性能提高
                                    if (i == 0) {
                                        mFragments.add(SimpleCardFragment.getInstance("0", title[i], title[i]));
                                    } else if (i == 1) {
                                        if (mSize >= 1) {
                                            mFragments.add(SimpleCardFragment.getInstance(mBeen.getData().get(0).getPosition(), mBeen.getData().get(0).getQrcode(), mBeen.getData().get(0).getMac()));
                                        } else {
                                            mFragments.add(SimpleCardFragment.getInstance("2", "", ""));
                                        }
                                    } else if (i == 2) {
                                        if (mSize >= 2) {
                                            mFragments.add(SimpleCardFragment.getInstance(mBeen.getData().get(1).getPosition(), mBeen.getData().get(1).getQrcode(), mBeen.getData().get(1).getMac()));
                                        } else {
                                            mFragments.add(SimpleCardFragment.getInstance("3", "", ""));
                                        }
                                    } else if (i == 3) {
                                        if (mSize >= 3) {
                                            mFragments.add(SimpleCardFragment.getInstance(mBeen.getData().get(2).getPosition(), mBeen.getData().get(2).getQrcode(), mBeen.getData().get(2).getMac()));
                                        } else {
                                            mFragments.add(SimpleCardFragment.getInstance("4", "", ""));
                                        }
                                    }
                                }
                                //一句代码就可以控制他是否可以左右滑动

                                Utils.runOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mViewPager.setNoScroll(true);
                                        mAdapter = new MyPagerAdapter(getSupportFragmentManager());
                                        mViewPager.setAdapter(mAdapter);
                                        mTabLayout.setViewPager(mViewPager, title);
                                    }
                                });

                            }
                        }
                    });

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //TODO:先判断是否登录了，并且注册完成了
            case R.id.money:
                skipOtherActivity(WalletActivity.class, false);
                break;
            //拨打电话
            case R.id.customer:
                hasPermission();
                android.app.AlertDialog.Builder builder2 = new android.app.AlertDialog.Builder(MainActivity.this);
                builder2.setMessage("拨打客服电话4000209777");
                builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //需要后台提供
                        tellPhone("4000209777");
                        dialog.dismiss();
                    }
                });
                android.app.AlertDialog dialog = builder2.create();
                dialog.show();
                break;
            case R.id.setting:

                skipOtherActivity(SettingActivity.class, false);
                break;
            case R.id.fix:
                skipOtherActivity(EquipFixActivity.class, false);
                break;

        }
    }

    private void tellPhone(String s) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ToastMake.showToast("拨打电话需要授权拨打电话");

            boolean showCallPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE);
            if (showCallPermission) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + s);
            intent.setData(data);
            startActivity(intent);
        }
    }

    private void hasPermission() {
        PermissionGen.with(MainActivity.this)
                .addRequestCode(READSDK)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CALL_PHONE
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = READSDK)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = READSDK)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean showCallPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE);
        if (showRequestPermission || showCallPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

    }

    private void UpdataApk() {
        int versionCode = getVersionCode();
        String versionNme = getVersionName();
        if (versionNme.contains(".")) {
            String[] vs_name = versionNme.split("\\.");

            for (int i = 0; i < vs_name.length; i++) {
                if (!vs_name[i].equals("")) {
                    if (i == 0) {
                        vs_name1 = Integer.valueOf(vs_name[0]);
                    }
                    if (i == 1) {
                        vs_name2 = Integer.valueOf(vs_name[1]);
                    }
                    if (i == 2) {
                        vs_name3 = Integer.valueOf(vs_name[2]);
                    }
                }
            }

        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .get()
                        .url(UriContect.VERSION)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                UpDataBeen dataBeen = GsonUtil.parseJsonToBean(response, UpDataBeen.class);
                                if (dataBeen == null) {
                                    return;
                                }
                                if (!TextUtils.equals(dataBeen.getStatus(), "1")) {

                                    return;
                                } else {
                                    String version = dataBeen.getVersion();
                                    final String url = dataBeen.getUrl();
                                    final String title = dataBeen.getTitle();
                                    final String msg = dataBeen.getMsg();
                                    if (version.contains(".")) {
                                        String[] sv_name = version.split("\\.");

                                        for (int i = 0; i < sv_name.length; i++) {

                                            if (!sv_name[i].equals("")) {
                                                if (i == 0) {
                                                    sv_name1 = Integer.valueOf(sv_name[0]);
                                                    System.out.println(sv_name1 + "");
                                                }
                                                if (i == 1) {
                                                    sv_name2 = Integer.valueOf(sv_name[1]);
                                                    System.out.println(sv_name2 + "");
                                                }
                                                if (i == 2) {
                                                    sv_name3 = Integer.valueOf(sv_name[2]);
                                                    System.out.println(sv_name3 + "");
                                                }
                                            }
                                        }
                                        if (vs_name1 > sv_name1) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    showDialog(title, msg, url);
                                                }
                                            });
                                        } else {
                                            if (vs_name2 > sv_name2) {

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        showDialog(title, msg, url);
                                                    }
                                                });

                                            } else {

                                                if (vs_name3 > sv_name3) {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            showDialog(title, msg, url);
                                                        }
                                                    });

                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        });
            }
        }).start();
    }

    private void downLoadApk(String url) {
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "chezai.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(call.toString());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        if (hasPermission) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                //判读版本是否在7.0以上
                                //新的启动方法
                                Uri apkUri = FileProvider.getUriForFile(MainActivity.this, getLocalClassName() + ".fileprovider", response);//在AndroidManifest中的android:authorities值
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                startActivity(install);
                            } else {
                                //以前的启动方法
                                // 通过Intent安装APK文件
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setDataAndType(Uri.fromFile(response.getAbsoluteFile()), "application/vnd.android.package-archive");
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(install);
                            }

                        } else {
                            ToastMake.showToast("请添加读取内存卡权限才能获得最新的版本");
                        }

                    }
                    @Override
                    public void inProgress(final float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        myProgress = (int) progress;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //TODO:可以自定义进度条
                                //                                ProgressBar progressBar = new ProgressBar(MainActivity.this, null, android.R.attr.progressBarStyleHorizontal);
                                //                                progressBar.setMax(100);
                                //                                progressBar.setProgress(myProgress);

                            }
                        });


                    }
                });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mDrawer.isDrawerOpen(GravityCompat.START)) {
                mDrawer.closeDrawer(GravityCompat.START);
                return true;
            }
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastMake.showToast(getResources().getString(R.string.string28));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取软件版本号
     *
     * @return
     */
    private int getVersionCode() {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    //TODO:进行版本升级操作

    /**
     * 获取版本名字
     *
     * @return
     */
    private String getVersionName() {
        String versionName = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    //弹出对话框
    private void showDialog(String title, String message, final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("取消升级");
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("确定升级");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //TODO:进行升级
                        downLoadApk(url);
                    }
                }).start();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private void showShare() {

        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(getString(R.string.string31));
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment("我是测试评论文本");
        // 启动分享GUI
        oks.show(this);
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return title[position];
        }

        @Override
        public Fragment getItem(int position) {


            return mFragments.get(position);
        }


    }
}
